var INOUT_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS INOUT (id INTEGER PRIMARY KEY AUTOINCREMENT,kind,firstname,lastname,amount,unit,startDate,endDate,comment)";
/**
 * The database
 */
var dbShell;
/**
 * Boolean for the state of the database tables (created or not) 
 */
var dbCreated=false;
/**
 * The HTML Generator
 */
var generator = new Generator();

/**
 * deviceready envent listener
 */
document.addEventListener("deviceready", function (){
	onDeviceReady();
}, false);

/**
 * Document ready event
 */
$( document ).ready(function() {

});

/**
 * onDeviceReady function
 */
function onDeviceReady(){
	
	dbShell = window.openDatabase("mainDB", "1","MoneyIODB",10000 );
	if(!dbCreated){//if database is not initialized
		dbShell.transaction(createTables,errorCB,successCB);
	}
    dbShell.transaction(queryDBHomeEntries,errorCB);
}

function createTables(tx){
	tx.executeSql(INOUT_TABLE_CREATE);
}

function queryDBHomeEntries(tx){
	tx.executeSql("SELECT * FROM INOUT",[],querySuccessHomeEntries,errorCB);
}

function querySuccessHomeEntries(tx, results){
	insertEntriesInDOM (results);
}

function deleteEntry(id){
	dbShell.transaction(function(tx){
		tx.executeSql("DELETE FROM INOUT WHERE id=\""+id+"\"");});
}


function errorCB(err)
{
	alert("SQL error:"+ err.message);
}
/**
 * When the tables are created
 * @returns {Boolean}
 */
function successCB()
{
	dbCreated = true;
	return true;
}


function insertEntriesInDOM (results){
	var list = "<li class=\"list-divider\">Home</li>";
	var len = results.rows.length;
	if(len == 0 ){
		$("ul#home").html(list+"<h3> Utilisez '+' pour ajouter une entree. </h3>");
		return;
	}
	for(var i = 0;i<len;i++){
		list += generator.generateHtmlForOneEntry(
				new MoneyIOEntry
				(results.rows.item(i).id, results.rows.item(i).kind, results.rows.item(i).firstname,
						results.rows.item(i).lastname, results.rows.item(i).startDate, 
						results.rows.item(i).endDate, results.rows.item(i).amount, 
						results.rows.item(i).unit, results.rows.item(i).comment));
	}
	$("ul#home").html(list);
	//add events to inserted elements 
	addEvents();
}


function addEvents(){
	$("li.entry a.action.delete").bind("tapone",function(event, obj){
		var id = $(this).closest("li.entry").attr('id');
		new fries.Dialog({
			selector:'#deleteDialog',
			callbackOk: function() {
				deleteEntry(id);
				dbShell.transaction(queryDBHomeEntries,errorCB);
				this.hide();
			},
			callbaclCancel: function(){
				this.hide();
			}
		}).show();
	});
}








